package com.example.backend.repository;

import com.example.backend.domain.entity.BatchOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.List;

/**
 * 批量操作Repository
 */
@Repository
public interface BatchOperationRepository extends JpaRepository<BatchOperation, Long> {

    /**
     * 根据操作者查找批量操作记录
     */
    Page<BatchOperation> findByOperatorIdOrderByCreatedAtDesc(Long operatorId, Pageable pageable);

    /**
     * 根据状态查找批量操作记录
     */
    List<BatchOperation> findByStatusOrderByCreatedAtDesc(String status);

    /**
     * 根据操作类型查找
     */
    Page<BatchOperation> findByOperationTypeOrderByCreatedAtDesc(String operationType, Pageable pageable);

    /**
     * 查找正在进行的批量操作
     */
    List<BatchOperation> findByStatusInOrderByCreatedAtAsc(List<String> statuses);

    /**
     * 统计操作者的批量操作数量
     */
    @Query("SELECT COUNT(bo) FROM BatchOperation bo WHERE bo.operator.id = :operatorId")
    Long countByOperatorId(@Param("operatorId") Long operatorId);

    /**
     * 统计成功完成的批量操作数量
     */
    @Query("SELECT COUNT(bo) FROM BatchOperation bo WHERE bo.operator.id = :operatorId AND bo.status = 'COMPLETED'")
    Long countSuccessfulOperationsByOperatorId(@Param("operatorId") Long operatorId);

    /**
     * 查找指定时间范围内的批量操作
     */
    @Query("SELECT bo FROM BatchOperation bo WHERE bo.createdAt BETWEEN :startDate AND :endDate ORDER BY bo.createdAt DESC")
    List<BatchOperation> findByCreatedAtBetween(@Param("startDate") Instant startDate, @Param("endDate") Instant endDate);

    /**
     * 查找失败的批量操作
     */
    @Query("SELECT bo FROM BatchOperation bo WHERE bo.status = 'FAILED' ORDER BY bo.createdAt DESC")
    List<BatchOperation> findFailedOperations();
}
